package org.dromara.bclt.websocket.controller;

import lombok.RequiredArgsConstructor;
import org.dromara.bclt.websocket.constant.ChatConstants;
import org.dromara.bclt.websocket.domain.ChatMessage;
import org.dromara.bclt.websocket.service.ChatService;
import org.dromara.common.core.domain.R;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 聊天控制器
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/chat")
public class ChatController extends BaseController {

    private final ChatService chatService;

    /**
     * 发送消息
     */
//    @Log(title = "聊天消息", businessType = BusinessType.INSERT)
    @PostMapping("/send/{receiverId}")
    public R<Boolean> sendMessage(@PathVariable Long receiverId, @RequestBody String content) {
        // 获取当前登录用户信息
        Long userId = LoginHelper.getUserId();
        String userName = LoginHelper.getUsername();
        String userType = String.valueOf(LoginHelper.getUserType());

        // 构建消息对象
        ChatMessage message = new ChatMessage();
        message.setType(ChatConstants.MESSAGE_TYPE_TEXT);
        message.setSenderId(userId);
        message.setSenderName(userName);
        message.setSenderType(userType.equals("sys_user") ? ChatConstants.SENDER_TYPE_DOCTOR : ChatConstants.SENDER_TYPE_PATIENT);
        message.setReceiverId(receiverId);
        message.setContent(content);
        message.setReadStatus(ChatConstants.MESSAGE_STATUS_UNREAD);

        // 发送消息
        boolean result = chatService.sendMessage(message);
        return R.ok(result);
    }

    /**
     * 获取聊天历史记录
     */
    @GetMapping("/history/{userId}")
    public R<List<ChatMessage>> getChatHistory(@PathVariable Long userId, @RequestParam(defaultValue = "20") Integer limit) {
        Long currentUserId = LoginHelper.getUserId();
        List<ChatMessage> history = chatService.getChatHistory(currentUserId, userId, limit);
        return R.ok(history);
    }

    /**
     * 标记消息为已读
     */
    @PostMapping("/read/{senderId}")
    public R<Integer> markAsRead(@PathVariable Long senderId) {
        Long currentUserId = LoginHelper.getUserId();
        int rows = chatService.markMessageAsRead(senderId, currentUserId);
        return R.ok(rows);
    }

    /**
     * 获取未读消息数量
     */
    @GetMapping("/unread/count")
    public R<Integer> getUnreadCount() {
        Long currentUserId = LoginHelper.getUserId();
        int count = chatService.getUnreadMessageCount(currentUserId);
        return R.ok(count);
    }
}
